#include "TagButtons.h"
#include <xmllite.h>


TagButtons::TagButtons(void)
{
}

TagButtons::~TagButtons(void)
{
}

bool TagButtons::Load(const CString& configFile)
{
	HRESULT hr;
	CComPtr<IStream> pFileStream;
	CComPtr<IXmlReader> pReader;
	XmlNodeType nodeType;
	const WCHAR* pName;
	const WCHAR* pValue;
 
	Items.clear();

	//Open XML document
	if (FAILED(hr = SHCreateStreamOnFile(configFile,  STGM_READ, &pFileStream)))
	{
		wprintf(L"Error opening XML document, error %08.8lx", hr);
		return false;
	}

	if (FAILED(hr = CreateXmlReader(__uuidof(IXmlReader), (void**)&pReader, NULL)))
	{
		wprintf(L"Error creating XmlReader, error %08.8lx", hr);
		return false;
	}

	if (FAILED(hr = pReader->SetInput(pFileStream)))
	{
		wprintf(L"Error setting input for XmlReader, error %08.8lx", hr);
		return false;
	}

	while (S_OK == (hr = pReader->Read(&nodeType))) 
	{
		switch (nodeType)
		{
			case XmlNodeType_Element:

				if (FAILED(hr = pReader->GetQualifiedName(&pName, NULL)))
				{
					wprintf(L"Error reading element name, error %08.8lx", hr);
					return false;
				}
				
				if (wcscmp(pName, L"tag") == 0)
				{
					CString name;
					CString hint;
					CString bitmap;
					CString customize;

					for (hr = pReader->MoveToFirstAttribute(); S_OK == hr; hr = pReader->MoveToNextAttribute())
					{
						if( FAILED(hr = pReader->GetQualifiedName(&pName, NULL)) ||
						    FAILED(hr = pReader->GetValue(&pValue, NULL)))
						{
							break;
						}

						if     (wcscmp(pName, L"name") == 0) name = pValue;
						else if(wcscmp(pName, L"hint") == 0) hint = pValue;
						else if(wcscmp(pName, L"bitmap") == 0) bitmap = pValue;
					    else if(wcscmp(pName, L"customize") == 0) customize = pValue;
					}
					
					if(name.GetLength() == 0) continue;

					// Modify bitmap path to make it point to the same directory as tags.xml
					TCHAR path [_MAX_PATH];
					TCHAR drive[_MAX_DRIVE];
					TCHAR dir  [_MAX_DIR];

					_wsplitpath_s(configFile,		drive,_MAX_DRIVE,	dir,   _MAX_DIR, 0,	0,	0,	0);
					_wmakepath_s (path,	_MAX_PATH,	drive,				dir,             bitmap,	0);

					bitmap = path;

					Items.push_back(TagButton(name, customize.GetLength() != 0, hint, bitmap));
				}	
					
			break;
		}
	}
	return true;
}
